package cn.smartravel.im.server;

import cn.smartravel.core.util.JsonUtil;
import cn.smartravel.im.entity.ImChatEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class ChatServer extends TextWebSocketHandler {

    private final static Map<String, ConcurrentWebSocketSessionDecorator> sessionDecoratorMap = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        String uid = (String) session.getAttributes().get(IMConst.FIELD_UID);
        if (sessionDecoratorMap.containsKey(uid))
            sessionDecoratorMap.remove(uid);
        sessionDecoratorMap.put(uid, new ConcurrentWebSocketSessionDecorator(session,
                IMConst.SEND_TIME_LIMIT,
                IMConst.BUFFER_SIZE_LIMIT));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //super.handleTextMessage(session, message);
        String messageJson = message.getPayload();
        log.debug("收到的消息：from = {}, message = {}",
                session.getAttributes().get(IMConst.FIELD_UID), messageJson);
        /* 发送消息到接受人*/
        ImChatEntity entity = JsonUtil.parseObject(messageJson, ImChatEntity.class);
        sessionDecoratorMap.get(entity.getReceiver()+ "").sendMessage(message);

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
    }
}
